package com.stockz.watchlist.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.stockz.core.model.Scrip;
import com.stockz.watchlist.model.WatchList;
import com.stockz.watchlist.model.WatchListEntry;

@Repository
@Transactional
@SuppressWarnings("unchecked")
public class WatchListDao {

	private EntityManager entityManager;
	
	@PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
	
	@Transactional(propagation=Propagation.MANDATORY)
	public void persist(WatchList watchList){
		entityManager.persist(watchList);
	}
	
	@Transactional(propagation=Propagation.MANDATORY)
	public void persist(WatchListEntry watchListEntry){
		entityManager.persist(watchListEntry);
	}
	
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public List<WatchList> getAll(){
		return entityManager.createQuery("from WatchList", WatchList.class).getResultList();
	}
	
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public List<WatchListEntry> getByWatchListId(Long id){
		Query query = entityManager.createNamedQuery(WatchListEntry.getEntriesByWatchListIdQuery, WatchListEntry.class);
		query.setParameter("id", id);
		return query.getResultList();
	}
	
	@Transactional(propagation=Propagation.MANDATORY, readOnly=true)
	public List<Scrip> getScripList(Long watchListId){
		String jpaql = "select s from Scrip s, WatchListEntry w where s.code = w.scrip.code and w.watchList.id = :watchListId";
		Query query = entityManager.createQuery(jpaql , Scrip.class);
		query.setParameter("watchListId", watchListId);
		return query.getResultList();
	}
	
	@Transactional(propagation=Propagation.MANDATORY)
	public void remove(Long watchListId){
		WatchList watchList = entityManager.find(WatchList.class,watchListId);
		if(watchList != null){
			entityManager.remove(watchList);
		}
	}
}
